package br.com.velp.vskygeo.filter;

import br.com.velp.vskygeo.dto.UsuarioLogadoDTO;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;

public class LoginFilter implements Filter {
    
    private static final String PAGINA_BLOQUEIO = "/acesso_negado.jsf";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

	HttpSession session = ((HttpServletRequest) request).getSession();
        Cookie[] theCookies = ((HttpServletRequest) request).getCookies();
        String urlRequest = ((HttpServletRequest) request).getRequestURI();
        
        if (urlRequest.contains(PAGINA_BLOQUEIO)){
            
            chain.doFilter(request, response);
            
        } else if (theCookies == null) {
            
            ((HttpServletResponse) response).sendRedirect(session.getServletContext().getContextPath() + PAGINA_BLOQUEIO);
            
        } else {
            
            UsuarioLogadoDTO usuarioLogado = new UsuarioLogadoDTO();
            
            for (Cookie cookie : theCookies) {

                if (cookie.getName().equals("usuario.logado") && StringUtils.isNotBlank("cookie.getValue()")){
                    usuarioLogado.setLogado(Boolean.valueOf(cookie.getValue()));
                }
                if (cookie.getName().equals("usuario.id") && StringUtils.isNotBlank("cookie.getValue()")){
                    usuarioLogado.setId(Integer.valueOf(cookie.getValue()));
                }
                if (cookie.getName().equals("usuario.nome") && StringUtils.isNotBlank("cookie.getValue()")){
                    usuarioLogado.setNome(cookie.getValue());
                }
                if (cookie.getName().equals("usuario.pesId") && StringUtils.isNotBlank("cookie.getValue()")){
                    usuarioLogado.setIdCliente(Integer.valueOf(cookie.getValue()));
                }
                if (cookie.getName().equals("usuario.funcao") && StringUtils.isNotBlank("cookie.getValue()")){
                    usuarioLogado.setFuncao(Integer.valueOf(cookie.getValue()));
                }

            }

            if (Boolean.TRUE.equals(usuarioLogado.getLogado())) {

                session.setAttribute("usuarioLogado", usuarioLogado);
                chain.doFilter(request, response);

            } else {

                ((HttpServletResponse) response).sendRedirect(session.getServletContext().getContextPath() + PAGINA_BLOQUEIO);

            }
            
        }
        
    }

    @Override
    public void destroy() {
    }

}
